#!/bin/bash -x

# This is the script for cloud-init, to run on a VM in unattended fashion. See run-benchmark.sh

export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y wget curl git jq

git clone --depth 1 'https://github.com/@repo@.git' --branch '@branch@' ClickBench
cd ClickBench/@system@

# The log will be sent to ClickHouse and processed then by materialized views:

echo -n 'System name: ' | tee -a log
jq -r '.system' template.json | tee -a log
echo -n 'Proprietary: ' | tee -a log
jq -r '.proprietary' template.json | tee -a log
echo -n 'Tuned: ' | tee -a log
jq -r '.tuned' template.json | tee -a log
echo -n 'Tags: ' | tee -a log
jq -c -r '.tags' template.json | tee -a log

echo -n 'Disk usage before: ' | tee -a log
df -B1 / | tail -n1 | awk '{ print $3 }' | tee -a log

timeout 20000 ./benchmark.sh 2>&1 | tee -a log

echo -n 'Disk usage after: ' | tee -a log
df -B1 / | tail -n1 | awk '{ print $3 }' | tee -a log
echo 'System: @system@' | tee -a log
echo -n 'Machine: ' | tee -a log
curl -sS -H "X-aws-ec2-metadata-token: $(curl -X PUT "http://169.254.169.254/latest/api/token" -sS -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")" 'http://169.254.169.254/latest/meta-data/instance-type' | tee -a log
echo | tee -a log
echo "Total time: $SECONDS" | tee -a log
du -b --max-depth=2 | tee -a log

# Save the results.
# First, prepare the database as in prepare-database.sql

RESULTS_URL="https://play.clickhouse.com/?user=sink&query=INSERT+INTO+data+FORMAT+RawBLOB"

curl ${RESULTS_URL} --data-binary @log
curl ${RESULTS_URL} --data-binary @/var/log/cloud-init-output.log

shutdown now
